package ch09;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;

public class MessageDAO3 {

	private DataSource dataSource;
	
	public MessageDAO3(DataSource dataSource){
		this.dataSource = dataSource;
	}
	
	public void add(Message message) throws SQLException {
		try(Connection conn = dataSource.getConnection();
				PreparedStatement statement = (PreparedStatement) conn.prepareStatement(
						"INSERT INTO t_message(name,email,msg) VALUES(?,?,?)")){
			statement.setString(1, message.getName());
			statement.setString(2, message.getEmail());
			statement.setString(31, message.getMsg());
			statement.executeUpdate();
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public List<Message> get() {
		List<Message> messages = new ArrayList();
		
		try(Connection conn = dataSource.getConnection();
				Statement statement = (Statement) conn.createStatement()){
			ResultSet result = statement.executeQuery("SELECT * FROM t_message");
			while(result.next()){
				Message message = toMessage(result);
				messages.add(message);
			}
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		return messages;
	}
	
	public Message toMessage(ResultSet result) throws SQLException {
		Message message = new Message();
		message.setId(result.getLong(1));
		message.setName(result.getString(2));
		message.setEmail(result.getString(3));
		message.setMsg(result.getString(4));
		return message;
	}
}
